package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.NavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements NavService {
    @Override
    public List<NavModel> getNavModelList() {
        Jedis jedis = new Jedis();
        jedis.select(10);
        List<NavModel> list = new ArrayList<>();
        boolean isHave = jedis.exists("navHref");
        if (isHave) {
            List<String> hrefs = jedis.lrange("navHref", 0, -1);
            List<String> titles = jedis.lrange("navTitle", 0, -1);
            for (int i = 0; i < hrefs.size(); i++
            ) {
                NavModel model = new NavModel();
                model.setHref(hrefs.get(i));
                model.setTitle(titles.get(i));
                list.add(model);
            }
            System.out.println("redis");
        } else {
            NavDao navDao = new NavImpl();
            list = navDao.getNavModelList();
            for (NavModel model : list
            ) {
                jedis.rpush("navHref", model.getHref());
                jedis.rpush("navTitle", model.getTitle());
            }
            System.out.println("mysql");
        }
        return list;
    }
//
//    public String add(CompanyModel companyModel) {
//        CompanyDao companyDao = new CompanyImpl();
//        int count = companyDao.add(companyModel);
//        if (count > 0) {
//            Jedis jedis = new Jedis();
//            jedis.del("companyid");
//        }
//        return count > 0 ? "success" : "error";
//    }

    public String update(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int count = navDao.update(navModel);
        if (count > 0) {
            Jedis jedis = new Jedis();
//            jedis.flushDB();//为了省事不推荐
            jedis.del("navHref", "navTitle");
        }
        return count > 0 ? "success" : "error";
    }

    public String delete(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int count = navDao.delete(navModel);
        if (count > 0) {
            Jedis jedis = new Jedis();
            jedis.select(10);
            jedis.del("navHref", "navTitle");
        }
        return count > 0 ? "success" : "error";
    }

}
